<?php

namespace app\common\model;

use think\Model;

class UserLevelRecord extends Model
{
    // 表名
    protected $name = 'user_level_record';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $updateTime = false;
    
    // 追加属性
    protected $append = [
        'create_time_text',
	    'old_level_text',
	    'new_level_text',
    ];
    
    
    
	public function getOldLevelTextAttr($value, $data) {
		$value = $value ? $value : $data['old_level'];
		$level = \app\admin\model\User::$_level;
		return isset($level[$value]) ? $level[$value] : '';
	}
	
	
	public function getNewLevelTextAttr($value, $data) {
		$value = $value ? $value : $data['new_level'];
		$level = \app\admin\model\User::$_level;
		return isset($level[$value]) ? $level[$value] : '';
	}


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['create_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }
	
    public function user(){
    	return $this->belongsTo('user', 'user_id', 'id', '', 'left')->setEagerlyType(0);
    }
	
	public function admin()
	{
		return $this->belongsTo('admin', 'admin_id', 'id', '', 'left')->setEagerlyType(0);
	}
	/**
	 * 添加升级记录
	 * @param $merid 商家号
	 * @param $userId 用户ID
	 * @param $oldLevel 之前等级
	 * @param $newLevel 新等级
	 * @param string $adminId 操作人
	 * @param string $remark 备注
	 * @return false|int
	 */
    public function addRecord($userId, $oldLevel, $newLevel, $adminId = '', $remark = '') {
        $data = [
        	'user_id' => $userId,
	        'admin_id' => $adminId,
	        'old_level' => $oldLevel,
	        'new_level' => $newLevel,
	        'remark' => $remark
        ];
        
        return $this->isUpdate(false)->save($data);
    }
}
